<template>
  <div class="app-container">
    <header>
      <el-button type="primary" size="mini" @click="addClick(null,null, '新增权限')">添加权限</el-button>
    </header>
    <section>
      <el-table
        :data="tableData"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="code" label="标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.pid === 0"
              type="text"
              size="small"
              @click="addClick(scope.row.id, null, '新增权限')"
            >添加</el-button>
            <el-button
              type="text"
              size="small"
              @click="addClick(scope.row.id, scope.row.pid, '编辑权限点')"
            >编辑</el-button>
            <el-button type="text" size="small" @click="delClick(scope.row.id,scope.row.pid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </section>
    <!-- 添加框 -->
    <addPermission ref="addPermission" @success="success" />
  </div>
</template>
<script>
import { getPermission, delPermission } from '@/api/permission'
import { dataToTree } from '@/utils/tools'
import addPermission from './components/addPermission.vue'
export default {
  name: 'Permission',
  components: {
    addPermission
  },
  data() {
    return {
      tableData: []

    }
  },
  created() {
    this.getPermission()
  },
  methods: {
    load(tree, treeNode, resolve) {
      setTimeout(() => {
        resolve([
          {
            id: 31,
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1519 弄'
          }, {
            id: 32,
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1519 弄'
          }
        ])
      }, 1000)
    },
    // 获取数据
    async getPermission() {
      const res = await getPermission()
      console.log(res)
      this.tableData = dataToTree(res.data)
    },
    // 删除
    delClick(id) {
      this.$confirm('确定要删除该数据吗？')
        .then(async _ => {
          await delPermission(id)
          this.getPermission()
          // 提示删除成功
          this.$message.success('删除权限成功！')
        })
        .catch(_ => {})
    },
    // 添加
    addClick(id, pid, str) {
      console.log(id)
      this.$refs.addPermission.open(id, pid, str)
    },
    // 新增、编辑操作成功后
    success() {
      this.getPermission()
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  padding: 10px;
  header {
    margin-left: auto;
    margin-bottom: 20px;
  }
}
</style>
